import axios from "axios" 
import { useUserInfoStore } from '@/store/userInfoState'
import { getToken } from "../utils/local"
import { remove } from "../utils/cookies"
import { ElMessage } from 'element-plus'

axios.defaults.timeout = 3000  //超时
//axios.defaults.baseURL = 'http://172.20.10.5:8080/'
axios.defaults.baseURL = 'http://localhost:8080/spring-boot/'
//axios.defaults.baseURL = 'http://10.96.116.33:8080/spring-boot/'
axios.defaults.headers.post['Authorization'] = 'application/x-www-form-urlencoded'


axios.interceptors.request.use( 
    config => {
        const store = useUserInfoStore()
        const token = store.token?store.token:getToken('token')
        token && (config.headers.token = token)
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
axios.interceptors.response.use(
     res => {
        if (res.data.errorCode) {
            return Promise.reject(res.data.errorText)
        } else if (res.data.code == '403') {
            remove()
            ElMessage.error('您还未登录呢，先去登录吧')
            location.reload()
            return Promise.reject('403')
        }
        return res
    }, 
    err =>{ 
        console.log('报错啦',err);
        if (err.code === "ECONNABORTED") {
            ElMessage.error('加载超时了，请稍后重试')
            return Promise.reject('500')
        } else if (err.code === "ERR_NETWORK") {
            ElMessage.error('您当前没有网络，请稍后重试')
            return Promise.reject('error')
        }
        return Promise.reject(err)
})

export function get(url:string,params?:object){
    return new Promise<void>((resolve, reject) => {
        axios.get(url,{ params }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

export function post(url:string,params:object){
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    return new Promise<void>((resolve, reject) => {
        axios.post(url,params).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}